package com.brotherly.util;

import java.util.Iterator;
import java.util.LinkedList;

public class ContentReader
{
    protected static final String begin = "$#";
    protected static final String end = "#$";

    protected LinkedList<String> sequences = new LinkedList<String>();

    protected String version;
    protected int count;

    protected ContentReader()
    {}

    public ContentReader(String content, String regex)
    {
        String[] seq = content.split(regex);

        for (int index = 0; index != seq.length; ++index)
        {
            String field = seq[index].trim();

            sequences.add(field);
        }
    }

    public ContentReader(String content)
    {
        String[] seq = content.split("\\|");

        if (seq.length < 3 || !seq[1].equals(begin))
        {
            version = "";
            count = -1;
            return;
        }

        boolean head = true;

        for (int index = 2; index != seq.length; ++index)
        {
            String field = seq[index].trim();

            if (field.equals(end))
                break;

            if (head)
            {
                if (field.indexOf(',') != -1)
                {
                    head = false;

                    count = Integer.valueOf(seq[index - 1]);

                    StringBuilder builder = new StringBuilder();

                    for (int jndex = 2; jndex < index - 1; ++jndex)
                    {
                        builder.append(seq[jndex]);
                    }

                    version = builder.toString();
                } else
                    continue;
            }

            sequences.add(field);
        }
    }

    public ContentReader shift()
    {
        sequences.removeFirst();
        return this;
    }

    public String getVersion()
    {
        return version;
    }

    public int getCountOfFields()
    {
        return count;
    }

    public String indexAt(int index)
    {
        return sequences.get(index);
    }

    public int size()
    {
        return sequences.size();
    }

    public ContentReader[] split(int size)
    {
        int count = sequences.size() / size;

        ContentReader[] subs = new ContentReader[count];

        int index = 0;
        Iterator<String> it = sequences.iterator();
        while (it.hasNext())
        {
            String field = it.next();
            ContentReader sub = subs[index / size];
            if (sub == null)
            {
                subs[index / size] = sub = new ContentReader();

                sub.version = version;
                sub.count = count;
            }

            sub.sequences.add(field);
            ++index;
        }

        return subs;
    }
}
